<template>
    <div class="container mx-auto p-4" style="height: 800px;">
      <!-- 搜索区域 -->
      <el-row :gutter="16" class="mb-4">
        <el-col :span="6">
          <el-form-item label="供应商类别" label-width="80px">
            <el-select v-model="searchForm.supplierType" placeholder="请选择" size="small">
              <el-option label="全部" value="" />
              <el-option label="广东" value="gd" />
              <el-option label="酒水饮料供应商" value="drink" />
              <el-option label="食品供应商" value="food" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="搜索关键词" label-width="80px">
            <el-input v-model="searchForm.keyword" placeholder="供应商编号/名称/联系人" size="small">
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="" label-width="0px">
            <el-checkbox v-model="searchForm.showDisabled" size="small">显示禁用供应商</el-checkbox>
          </el-form-item>
        </el-col>
        <el-col :span="6" class="flex justify-end">
          <el-button type="primary" size="small" @click="handleQuery">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          <el-button type="text" size="small" @click="handleManage">
            <el-icon><Setting /></el-icon> 供应商管理
          </el-button>
        </el-col>
      </el-row>
  
      <!-- 操作按钮 -->
      <div class="mb-4 flex flex-wrap gap-2">
        <el-button type="primary" size="small" @click="handleAdd">
          <el-icon><Plus /></el-icon> 新增
        </el-button>
        <el-button type="primary" size="small" @click="handleBatchEdit">
          <el-icon><Edit /></el-icon> 批量修改
        </el-button>
        <el-button type="primary" size="small" @click="handleDisable">
          <el-icon><Close /></el-icon> 禁用
        </el-button>
        <el-button type="primary" size="small" @click="handleEnable">
          <el-icon><Check /></el-icon> 启用
        </el-button>
        <el-button type="primary" size="small" @click="handleImport">
          <el-icon><Upload /></el-icon> 导入
        </el-button>
        <el-button type="primary" size="small" @click="handleExport">
          <el-icon><Download /></el-icon> 导出
        </el-button>
        <el-button type="danger" size="small" @click="handleDelete">
          <el-icon><Delete /></el-icon> 删除
        </el-button>
      </div>
  
      <!-- 新增供应商对话框 -->
      <el-dialog title="新增供应商" v-model="addDialogVisible" width="600px">
        <div class="dialog-content">
          <el-form label-width="80px">
            <el-form-item label="类型">
              <el-radio-group v-model="form.type">
                <el-radio label="供应商">供应商</el-radio>
                <el-radio label="客户/供应商">客户/供应商</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="供应商编号" required>
              <el-input v-model="form.supplierCode" placeholder="请输入供应商编号"></el-input>
            </el-form-item>
            <el-form-item label="供应商名称" required>
              <el-input v-model="form.supplierName" placeholder="请输入供应商名称"></el-input>
            </el-form-item>
            <el-form-item label="供应商类别">
              <el-input v-model="form.supplierCategory" placeholder="请输入供应商类别"></el-input>
            </el-form-item>
            <el-form-item label="余额日期">
              <el-date-picker
                v-model="form.balanceDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item label="期初应付款">
              <el-input v-model="form.initialPayable" placeholder="请输入期初应付款"></el-input>
            </el-form-item>
            <el-form-item label="期初预付款">
              <el-input v-model="form.initialPrepayment" placeholder="请输入期初预付款"></el-input>
            </el-form-item>
            <el-form-item label="增值税税率">
              <el-input v-model="form.taxRate" placeholder="请输入增值税税率"></el-input>
            </el-form-item>
            <el-form-item label="纳税人识别号">
              <el-input v-model="form.taxId" placeholder="请输入纳税人识别号"></el-input>
            </el-form-item>
            <el-form-item label="开户银行">
              <el-input v-model="form.bankName" placeholder="请输入开户银行"></el-input>
            </el-form-item>
            <el-form-item label="银行账号">
              <el-input v-model="form.bankAccount" placeholder="请输入银行账号"></el-input>
            </el-form-item>
            <el-form-item label="交货方式">
              <el-input v-model="form.deliveryMethod" placeholder="请输入交货方式"></el-input>
            </el-form-item>
            <el-form-item label="是否物流公司">
              <el-select v-model="form.isLogistics" placeholder="请选择">
                <el-option label="是" value="是"></el-option>
                <el-option label="否" value="否"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="业务员">
              <el-input v-model="form.salesman" placeholder="请输入业务员"></el-input>
            </el-form-item>
            <el-form-item label="附件">
              <el-upload
                class="upload-demo"
                action="#"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :file-list="fileList"
                accept=".xls,.xlsx,.doc,.docx,.pdf"
              >
                <el-button type="primary" size="small">
                  <el-icon><Upload /></el-icon> 上传附件
                </el-button>
              </el-upload>
            </el-form-item>
            <el-form-item label="联系人信息">
              <el-table
                :data="contactList"
                border
                size="small"
                style="width: 100%"
              >
                <el-table-column label="联系人" prop="contactName" width="100" />
                <el-table-column label="手机" prop="phone" width="120" />
                <el-table-column label="座机" prop="tel" width="120" />
                <el-table-column label="QQ/微信/Email" prop="qqWechatEmail" width="140" />
                <el-table-column label="联系地址" prop="address" width="180" />
                <el-table-column label="首要联系人" prop="isPrimary" width="100">
                  <template #default="scope">
                    <el-checkbox v-model="scope.row.isPrimary"></el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template #default="scope">
                    <el-button
                      type="text"
                      size="mini"
                      @click="handleDeleteContact(scope.row)"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-button
                type="text"
                size="small"
                class="mt-2"
                @click="addContact"
              >
                <el-icon><Plus /></el-icon> 添加新联系人
              </el-button>
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入备注信息"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave">保存</el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 表格区域 - 带滚动条 -->
      <div class="scroll-container">
        <el-table
          :data="tableData"
          border
          size="small"
          height="500"
          :row-class-name="tableRowClassName"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <div class="flex justify-center gap-1">
                <el-button type="text" size="mini" @click="handleEdit(scope.row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button type="text" size="mini" @click="handleDeleteRow(scope.row)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="supplierType" label="供应商类别" width="100" />
          <el-table-column prop="supplierCode" label="供应商编号" width="100" />
          <el-table-column prop="supplierName" label="供应商名称" width="140" />
          <el-table-column prop="salesman" label="业务员" width="80" />
          <el-table-column prop="mainContact" label="首要联系人" width="100" />
          <el-table-column prop="taxRate" label="增值税税率" width="100" />
          <el-table-column prop="bankAccount" label="银行账号" width="160" />
          <el-table-column prop="bankName" label="开户银行" width="100" />
          <el-table-column prop="taxId" label="纳税人识别号" width="140" />
          <el-table-column prop="phone" label="手机" width="120" />
          <el-table-column prop="tel" label="座机" width="120" />
          <el-table-column prop="qqWechatEmail" label="QQ/微信/Email" width="140" />
          <el-table-column prop="address" label="联系地址" width="180" />
          <el-table-column prop="remark" label="备注" width="100" />
          <el-table-column prop="payableBalance" label="应付款余额" width="120" />
          <el-table-column prop="status" label="状态" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.status === '启用' ? 'success' : 'danger'">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="isLogistics" label="是否物流公司" width="120" />
          <el-table-column prop="isRelateLogistics" label="是否关联系物流公司" width="140" />
        </el-table>
      </div>
  
      <!-- 分页 -->
      <el-pagination
        class="mt-4 flex justify-end"
        background
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  
  // 搜索表单
  const searchForm = ref({
    supplierType: '',
    keyword: '',
    showDisabled: false
  })
  
  // 表格数据
  const tableData = ref([
    {
      id: 1,
      supplierType: '广东',
      supplierCode: 'G00001',
      supplierName: '商品综合批发有限公司',
      salesman: '张三',
      mainContact: '王经理',
      taxRate: 9,
      bankAccount: 'ENCR **** **** **** **** r2Ph',
      bankName: '工商银行广州分行',
      taxId: '91144030035***92H',
      phone: '18012340000',
      tel: '020-12345678',
      qqWechatEmail: 'wang@example.com',
      address: '广东省广州市天河区百合路88号',
      remark: '主要食品供应商',
      payableBalance: 13881.78,
      status: '启用',
      isLogistics: '否',
      isRelateLogistics: '否'
    },
    {
      id: 2,
      supplierType: '酒水饮料供应商',
      supplierCode: 'G00002',
      supplierName: '岭南酒水有限公司',
      salesman: '李四',
      mainContact: '李总监',
      taxRate: 13,
      bankAccount: 'ENCR **** **** **** **** t5Yh',
      bankName: '建设银行广州分行',
      taxId: '91144030036***93J',
      phone: '18012341111',
      tel: '020-12345679',
      qqWechatEmail: 'li@example.com',
      address: '广东省广州市越秀区北京路100号',
      remark: '高端酒水供应商',
      payableBalance: 25600.50,
      status: '启用',
      isLogistics: '否',
      isRelateLogistics: '否'
    },
    {
      id: 3,
      supplierType: '食品供应商',
      supplierCode: 'G00003',
      supplierName: '美味食品加工厂',
      salesman: '王五',
      mainContact: '赵师傅',
      taxRate: 9,
      bankAccount: 'ENCR **** **** **** **** u7Ki',
      bankName: '农业银行广州分行',
      taxId: '91144030037***94K',
      phone: '18012342222',
      tel: '020-12345680',
      qqWechatEmail: 'zhao@example.com',
      address: '广东省广州市海珠区新港路150号',
      remark: '速冻食品供应商',
      payableBalance: 8950.25,
      status: '禁用',
      isLogistics: '否',
      isRelateLogistics: '否'
    }
  ])
  
  // 分页信息
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(tableData.value.length)
  
  // 选中的行
  const multipleSelection = ref([])
  
  // 新增对话框相关
  const addDialogVisible = ref(false)
  // 表单数据
  const form = ref({
    type: '供应商',
    supplierCode: '',
    supplierName: '',
    supplierCategory: '',
    balanceDate: '',
    initialPayable: '',
    initialPrepayment: '',
    taxRate: '',
    taxId: '',
    bankName: '',
    bankAccount: '',
    deliveryMethod: '',
    isLogistics: '否',
    salesman: '',
    remark: ''
  })
  // 附件列表
  const fileList = ref([])
  // 联系人列表
  const contactList = ref([
    {
      contactName: '',
      phone: '',
      tel: '',
      qqWechatEmail: '',
      address: '',
      isPrimary: false
    }
  ])
  
  // 生命周期钩子
  onMounted(() => {
    loadTableData()
  })
  
  // 加载表格数据
  const loadTableData = () => {
    console.log('加载第', currentPage.value, '页数据，每页', pageSize.value, '条')
    total.value = tableData.value.length
  }
  
  // 表格行样式
  const tableRowClassName = ({ rowIndex }) => {
    return rowIndex % 2 === 0 ? 'bg-gray-50' : ''
  }
  
  // 处理选择变化
  const handleSelectionChange = (val) => {
    multipleSelection.value = val
  }
  
  // 按钮事件处理
  const handleQuery = () => {
    console.log('执行查询:', searchForm.value)
    currentPage.value = 1
    loadTableData()
  }
  
  const handleManage = () => {
    console.log('进入供应商管理页面')
  }
  
  const handleAdd = () => {
    addDialogVisible.value = true
    resetForm()
  }
  
  const handleBatchEdit = () => {
    if (multipleSelection.value.length === 0) {
      ElMessage.warning('请先选择要操作的供应商')
      return
    }
    console.log('批量修改选中项:', multipleSelection.value)
  }
  
  const handleDisable = () => {
    if (multipleSelection.value.length === 0) {
      ElMessage.warning('请先选择要操作的供应商')
      return
    }
    ElMessageBox.confirm(
      `确定要禁用选中的 ${multipleSelection.value.length} 个供应商吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      multipleSelection.value.forEach(item => {
        item.status = '禁用'
      })
      ElMessage.success('禁用成功')
    }).catch(() => {
      ElMessage.info('已取消禁用')
    })
  }
  
  const handleEnable = () => {
    if (multipleSelection.value.length === 0) {
      ElMessage.warning('请先选择要操作的供应商')
      return
    }
    ElMessageBox.confirm(
      `确定要启用选中的 ${multipleSelection.value.length} 个供应商吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      multipleSelection.value.forEach(item => {
        item.status = '启用'
      })
      ElMessage.success('启用成功')
    }).catch(() => {
      ElMessage.info('已取消启用')
    })
  }
  
  const handleImport = () => {
    ElMessage.info('导入功能开发中...')
  }
  
  const handleExport = () => {
    ElMessage.info('导出功能开发中...')
  }
  
  const handleDelete = () => {
    if (multipleSelection.value.length === 0) {
      ElMessage.warning('请先选择要删除的供应商')
      return
    }
    ElMessageBox.confirm(
      `确定要删除选中的 ${multipleSelection.value.length} 个供应商吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    ).then(() => {
      const ids = multipleSelection.value.map(item => item.id)
      tableData.value = tableData.value.filter(item => !ids.includes(item.id))
      multipleSelection.value = []
      ElMessage.success('删除成功')
      loadTableData()
    }).catch(() => {
      ElMessage.info('已取消删除')
    })
  }
  
  const handleEdit = (row) => {
    console.log('编辑供应商ID:', row.id)
    addDialogVisible.value = true
    form.value = { ...row }
    contactList.value = row.contacts || [
      {
        contactName: row.mainContact || '',
        phone: row.phone || '',
        tel: row.tel || '',
        qqWechatEmail: row.qqWechatEmail || '',
        address: row.address || '',
        isPrimary: true
      }
    ]
  }
  
  const handleDeleteRow = (row) => {
    ElMessageBox.confirm(
      `确定要删除供应商 "${row.supplierName}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      const index = tableData.value.findIndex(item => item.id === row.id)
      if (index !== -1) {
        tableData.value.splice(index, 1)
        ElMessage.success('删除成功')
        loadTableData()
      }
    }).catch(() => {
      ElMessage.info('已取消删除')
    })
  }
  
  // 分页事件处理
  const handleSizeChange = (val) => {
    pageSize.value = val
    loadTableData()
  }
  
  const handleCurrentChange = (val) => {
    currentPage.value = val
    loadTableData()
  }
  
  // 新增对话框相关方法
  // 重置表单
  const resetForm = () => {
    form.value = {
      type: '供应商',
      supplierCode: '',
      supplierName: '',
      supplierCategory: '',
      balanceDate: '',
      initialPayable: '',
      initialPrepayment: '',
      taxRate: '',
      taxId: '',
      bankName: '',
      bankAccount: '',
      deliveryMethod: '',
      isLogistics: '否',
      salesman: '',
      remark: ''
    }
    fileList.value = []
    contactList.value = [
      {
        contactName: '',
        phone: '',
        tel: '',
        qqWechatEmail: '',
        address: '',
        isPrimary: false
      }
    ]
  }
  
  // 上传附件预览
  const handlePreview = (file) => {
    console.log('预览文件:', file)
  }
  
  // 上传附件移除
  const handleRemove = (file, fileList) => {
    console.log('移除文件:', file, '当前列表:', fileList)
  }
  
  // 添加新联系人
  const addContact = () => {
    contactList.value.push({
      contactName: '',
      phone: '',
      tel: '',
      qqWechatEmail: '',
      address: '',
      isPrimary: false
    })
  }
  
  // 删除联系人
  const handleDeleteContact = (row) => {
    const index = contactList.value.findIndex(item => item === row)
    if (index !== -1) {
      contactList.value.splice(index, 1)
    }
    if (contactList.value.length < 1) {
      addContact()
    }
  }
  
  // 表单验证
  const validateForm = () => {
    if (!form.value.supplierCode) {
      ElMessage.error('供应商编号不能为空')
      return false
    }
    if (!form.value.supplierName) {
      ElMessage.error('供应商名称不能为空')
      return false
    }
    if (!form.value.taxId) {
      ElMessage.error('纳税人识别号不能为空')
      return false
    }
    if (form.value.initialPayable && isNaN(Number(form.value.initialPayable))) {
      ElMessage.error('期初应付款必须为数字')
      return false
    }
    if (form.value.initialPrepayment && isNaN(Number(form.value.initialPrepayment))) {
      ElMessage.error('期初预付款必须为数字')
      return false
    }
    if (form.value.taxRate && isNaN(Number(form.value.taxRate))) {
      ElMessage.error('增值税税率必须为数字')
      return false
    }
    return true
  }
  
  // 保存新增数据
  const handleSave = () => {
    if (!validateForm()) return
    
    const newSupplier = {
      ...form.value,
      contacts: contactList.value.filter(item => item.contactName),
      files: fileList.value.map(file => ({
        name: file.name,
        size: file.size,
        type: file.type
      })),
      status: '启用',
      payableBalance: 0,
      // 生成唯一ID（实际项目中由后端生成）
      id: Date.now()
    }
    
    console.log('提交的供应商数据:', newSupplier)
    
    // 模拟接口请求
    setTimeout(() => {
      tableData.value.unshift(newSupplier)
      ElMessage.success('保存成功')
      addDialogVisible.value = false
      loadTableData()
    }, 500)
  }
  </script>
  
  <style scoped>
  .container {
    min-width: 1200px;
  }
  
  .flex {
    display: flex;
  }
  
  .justify-end {
    justify-content: flex-end;
  }
  
  .mb-4 {
    margin-bottom: 16px;
  }
  
  .mt-2 {
    margin-top: 8px;
  }
  
  .bg-gray-50 {
    background-color: #f5f7fa;
  }
  
  .dialog-content {
    padding: 20px;
  }
  
  .upload-demo {
    width: 100%;
  }
  
  .scroll-container {
    overflow: auto;
    max-height: 500px;
    scrollbar-width: thin;
    scrollbar-color: #c1c1c1 #f8f8f8;
  }
  
  .scroll-container::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }
  
  .scroll-container::-webkit-scrollbar-track {
    background: #f8f8f8;
  }
  
  .scroll-container::-webkit-scrollbar-thumb {
    background-color: #c1c1c1;
    border-radius: 3px;
  }
  
  :deep(.el-table) {
    font-size: 12px !important;
  }
  
  :deep(.el-form-item__label) {
    font-size: 12px !important;
  }
  
  :deep(.el-input__inner) {
    font-size: 12px !important;
  }
  
  :deep(.el-select__input) {
    font-size: 12px !important;
  }
  
  :deep(.el-button) {
    font-size: 12px !important;
  }
  
  :deep(.el-pagination) {
    font-size: 12px !important;
  }
  
  :deep(.el-tag) {
    font-size: 12px !important;
  }
  </style>